#include "Greedy4.h"

void Greedy4::nextStep() {
    int nid = nodeToExplore();
    TVec<TInt> rec;
    if (visit[nid].Val1 > visit[nid].Val2) {
      network->getFollowers(nid, rec, visit[nid].Val3);
      visit[nid].Val1 -= rec.Len();
      visit[nid].Val3 += rec.Len();
      if (visit[nid].Val1 != 0) {
	q.push(TIntPr(visit[nid].Val1, nid));
      }
    } else {
      network->getFollowees(nid, rec, visit[nid].Val4);
      visit[nid].Val2 -= rec.Len();
      visit[nid].Val4 += rec.Len();
      if (visit[nid].Val2 != 0) {
	q.push(TIntPr(visit[nid].Val2, nid));
      }
    }
    for(TVec<TInt>::TIter i = rec.BegI(); i != rec.EndI(); i++)
        updateDiscoveredNode(i->Val);
    TIntPr p = network->evaluate();
    int totalCost = network->getTotalCost();
    //if(totalCost % 1000 == 0){
    nodeRecall.Add(TFltPr(network->getTotalCost(), double(p.Val1)));
    edgeRecall.Add(TFltPr(network->getTotalCost(), double(p.Val2)));
    //}
}

int Greedy4::nodeToExplore() {
  int nid;
  if (!q.empty()) {
    nid = q.top().Val2;
    q.pop();
  } else {
    nid = network->getTeleportNode();
    updateDiscoveredNode(nid);
  }
  return nid;
}

void Greedy4::updateDiscoveredNode(int discoveredNode) {
  if (visit.find(discoveredNode) == visit.end()) {
    TIntV ret1, ret2;
    TIntPr deg;
    network->getFollowers(discoveredNode, ret1);
    deg.Val1 = ret1.Len();
    network->getFollowees(discoveredNode, ret2);
    deg.Val2 = ret2.Len();
    if (deg.Val1 >= C || deg.Val2 >= C)
      deg = network->getDegree(discoveredNode);
    q.push(TIntPr(deg.Val1, discoveredNode));
    q.push(TIntPr(deg.Val2, discoveredNode));
    visit[discoveredNode] = TIntQu(deg.Val1, deg.Val2, 0, 0);
  }
}

